home *** CD-ROM | disk | FTP | other *** search
/ Skunkware 98 / Skunkware 98.iso / osr5 / sco / scripts / groups < prev    next >
Encoding:
AWK Script  |  1997-08-26  |  28.9 KB  |  785 lines

  1. #!/usr/local/bin/gawk -f
  2. # @(#) groups.gawk 2.0 95/09/15
  3. # 90/05/29 john h. dubois iii (john@armory.com)
  4. # 95/09/15 Converted to gawk program.  Cleaned up.
  5. BEGIN {
  6.     Name = "groups"
  7.     Usage = "Usage: " Name " [-ha] [user ...]"
  8.     ARGC = Opts(Name,Usage,"xha")
  9.     if (Debug = "x" in Options)
  10.     print "Debug is on." > "/dev/stderr"
  11.     if ("h" in Options) {
  12.     printf \
  13. "%s: list login and supplemental groups that users belong to.\n"\
  14. "%s\n"\
  15. "The groups that any of the users is a member of at login time (both the\n"\
  16. "login group and the supplemental groups) are listed.  If no users are\n"\
  17. "given, the groups the invoking user is in are listed.  grep-style syntax\n"\
  18. "may be used to match users; patterns should be quoted to protect them from\n"\
  19. "the shell.\n"\
  20. "Options:\n"\
  21. "-h: Print this help.\n"\
  22. "-a: For each group in the output, print the line for the group from\n"\
  23. "    /etc/group, which gives the group name, its password (if any), its\n"\
  24. "    group id, and a list of everyone in the group.\n",Name,Usage
  25.     exit 0
  26.     }
  27.     if (ARGC > 1)
  28.     for (i = 1; i < ARGC; i++)
  29.         Users[ARGV[i]]
  30.     else {
  31. # /dev/user is broken in gawk 2.15.6; gives fatal error for non-root user
  32. #    if (Debug)
  33. #        print "Reading from /dev/user..." > "/dev/stderr"
  34. #    if ((getline < "/dev/user") != 1) {
  35. #        print "Could not get UID.  Exiting." > "/dev/stderr"
  36. #        exit 1
  37. #    }
  38. #    if (Debug)
  39. #        printf "UID is %d\n",$1 > "/dev/stderr"
  40. #    UIDs[$1]
  41.     id(IDs)
  42.     Users[IDs["user"]]
  43.     }
  44.     FS = ":"
  45.     while (getline < "/etc/passwd")
  46.     if ($1 in Users || $3 in UIDs) {
  47.         lgroups[$4]
  48.         UserPat = UserPat "|" $1
  49.     }
  50.     UserPat = "(^|,)(" substr(UserPat,2) ")([, \t]|$)"
  51.     close("/etc/passwd")
  52.     Full = "a" in Options
  53.     while (getline < "/etc/group")
  54.     if ($3 in lgroups || $4 ~ UserPat)
  55.         if (Full)
  56.         print $0
  57.         else
  58.         print $1
  59. }
  60.  
  61. ### Start of ProcArgs library
  62. # @(#) ProcArgs 1.11 96/12/08
  63. # 92/02/29 john h. dubois iii (john@armory.com)
  64. # 93/07/18 Added "#" arg type
  65. # 93/09/26 Do not count -h against MinArgs
  66. # 94/01/01 Stop scanning at first non-option arg.  Added ">" option type.
  67. #          Removed meaning of "+" or "-" by itself.
  68. # 94/03/08 Added & option and *()< option types.
  69. # 94/04/02 Added NoRCopt to Opts()
  70. # 94/06/11 Mark numeric variables as such.
  71. # 94/07/08 Opts(): Do not require any args if h option is given.
  72. # 95/01/22 Record options given more than once.  Record option num in argv.
  73. # 95/06/08 Added ExclusiveOptions().
  74. # 96/01/20 Let rcfiles be a colon-separated list of filenames.
  75. #          Expand $VARNAME at the start of its filenames.
  76. #          Let varname=0 and -option- turn off an option.
  77. # 96/05/05 Changed meaning of 7th arg to Opts; now can specify exactly how many
  78. #          of the vars should be searched for in the environment.
  79. #          Check for duplicate rcfiles.
  80. # 96/05/13 Return more specific error values.  Note: ProcArgs() and InitOpts()
  81. #          now return various negatives values on error, not just -1, and
  82. #          Opts() may set Err to various positive values, not just 1.
  83. #          Added AllowUnrecOpt.
  84. # 96/05/23 Check type given for & option
  85. # 96/06/15 Re-port to awk
  86. # 96/10/01 Moved file-reading code into ReadConfFile(), so that it can be
  87. #          used by other functions.
  88. # 96/10/15 Added OptChars
  89. # 96/11/01 Added exOpts arg to Opts()
  90. # 96/11/16 Added ; type
  91. # 96/12/08 Added Opt2Set() & Opt2Sets()
  92. # 96/12/27 Added CmdLineOpt()
  93.  
  94. # optlist is a string which contains all of the possible command line options.
  95. # A character followed by certain characters indicates that the option takes
  96. # an argument, with type as follows:
  97. # :    String argument
  98. # ;    Non-empty string argument
  99. # *    Floating point argument
  100. # (    Non-negative floating point argument
  101. # )    Positive floating point argument
  102. # #    Integer argument
  103. # <    Non-negative integer argument
  104. # >    Positive integer argument
  105. # The only difference the type of argument makes is in the runtime argument
  106. # error checking that is done.
  107.  
  108. # The & option is a special case used to get numeric options without the
  109. # user having to give an option character.  It is shorthand for [-+.0-9].
  110. # If & is included in optlist and an option string that begins with one of
  111. # these characters is seen, the value given to "&" will include the first
  112. # char of the option.  & must be followed by a type character other than ":"
  113. # or ";".
  114. # Note that if e.g. &> is given, an option of -.5 will produce an error.
  115.  
  116. # Strings in argv[] which begin with "-" or "+" are taken to be
  117. # strings of options, except that a string which consists solely of "-"
  118. # or "+" is taken to be a non-option string; like other non-option strings,
  119. # it stops the scanning of argv and is left in argv[].
  120. # An argument of "--" or "++" also stops the scanning of argv[] but is removed.
  121. # If an option takes an argument, the argument may either immediately
  122. # follow it or be given separately.
  123. # "-" and "+" options are treated the same.  "+" is allowed because most awks
  124. # take any -options to be arguments to themselves.  gawk 2.15 was enhanced to
  125. # stop scanning when it encounters an unrecognized option, though until 2.15.5
  126. # this feature had a flaw that caused problems in some cases.  See the OptChars
  127. # parameter to explicitly set the option-specifier characters.
  128.  
  129. # If an option that does not take an argument is given,
  130. # an index with its name is created in Options and its value is set to the
  131. # number of times it occurs in argv[].
  132.  
  133. # If an option that does take an argument is given, an index with its name is
  134. # created in Options and its value is set to the value of the argument given
  135. # for it, and Options[option-name,"count"] is (initially) set to the 1.
  136. # If an option that takes an argument is given more than once,
  137. # Options[option-name,"count"] is incremented, and the value is assigned to
  138. # the index (option-name,instance) where instance is 2 for the second occurance
  139. # of the option, etc.
  140. # In other words, the first time an option with a value is encountered, the
  141. # value is assigned to an index consisting only of its name; for any further
  142. # occurances of the option, the value index has an extra (count) dimension.
  143.  
  144. # The sequence number for each option found in argv[] is stored in
  145. # Options[option-name,"num",instance], where instance is 1 for the first
  146. # occurance of the option, etc.  The sequence number starts at 1 and is
  147. # incremented for each option, both those that have a value and those that
  148. # do not.  Options set from a config file have a value of 0 assigned to this.
  149.  
  150. # Options and their arguments are deleted from argv.
  151. # Note that this means that there may be gaps left in the indices of argv[].
  152. # If compress is nonzero, argv[] is packed by moving its elements so that
  153. # they have contiguous integer indices starting with 0.
  154. # Option processing will stop with the first unrecognized option, just as
  155. # though -- was given except that unlike -- the unrecognized option will not be
  156. # removed from ARGV[].  Normally, an error value is returned in this case.
  157. # If AllowUnrecOpt is true, it is not an error for an unrecognized option to
  158. # be found, so the number of remaining arguments is returned instead.
  159. # If OptChars is not a null string, it is the set of characters that indicate
  160. # that an argument is an option string if the string begins with one of the
  161. # characters.  A string consisting solely of two of the same option-indicator
  162. # characters stops the scanning of argv[].  The default is "-+".
  163. # argv[0] is not examined.
  164. # The number of arguments left in argc is returned.
  165. # If an error occurs, the global string OptErr is set to an error message
  166. # and a negative value is returned.
  167. # Current error values:
  168. # -1: option that required an argument did not get it.
  169. # -2: argument of incorrect type supplied for an option.
  170. # -3: unrecognized (invalid) option.
  171. function ProcArgs(argc,argv,OptList,Options,compress,AllowUnrecOpt,OptChars,
  172. ArgNum,ArgsLeft,Arg,ArgLen,ArgInd,Option,Pos,NumOpt,Value,HadValue,specGiven,
  173. NeedNextOpt,GotValue,OptionNum,Escape,dest,src,count,c,OptTerm,OptCharSet)
  174. {
  175. # ArgNum is the index of the argument being processed.
  176. # ArgsLeft is the number of arguments left in argv.
  177. # Arg is the argument being processed.
  178. # ArgLen is the length of the argument being processed.
  179. # ArgInd is the position of the character in Arg being processed.
  180. # Option is the character in Arg being processed.
  181. # Pos is the position in OptList of the option being processed.
  182. # NumOpt is true if a numeric option may be given.
  183.     ArgsLeft = argc
  184.     NumOpt = index(OptList,"&")
  185.     OptionNum = 0
  186.     if (OptChars == "")
  187.     OptChars = "-+"
  188.     while (OptChars != "") {
  189.     c = substr(OptChars,1,1)
  190.     OptChars = substr(OptChars,2)
  191.     OptCharSet[c]
  192.     OptTerm[c c]
  193.     }
  194.     for (ArgNum = 1; ArgNum < argc; ArgNum++) {
  195.     Arg = argv[ArgNum]
  196.     if (length(Arg) < 2 || !((specGiven = substr(Arg,1,1)) in OptCharSet))
  197.         break    # Not an option; quit
  198.     if (Arg in OptTerm) {
  199.         delete argv[ArgNum]
  200.         ArgsLeft--
  201.         break
  202.     }
  203.     ArgLen = length(Arg)
  204.     for (ArgInd = 2; ArgInd <= ArgLen; ArgInd++) {
  205.         Option = substr(Arg,ArgInd,1)
  206.         if (NumOpt && Option ~ /[-+.0-9]/) {
  207.         # If this option is a numeric option, make its flag be & and
  208.         # its option string flag position be the position of & in
  209.         # the option string.
  210.         Option = "&"
  211.         Pos = NumOpt
  212.         # Prefix Arg with a char so that ArgInd will point to the
  213.         # first char of the numeric option.
  214.         Arg = "&" Arg
  215.         ArgLen++
  216.         }
  217.         # Find position of flag in option string, to get its type (if any).
  218.         # Disallow & as literal flag.
  219.         else if (!(Pos = index(OptList,Option)) || Option == "&") {
  220.         if (AllowUnrecOpt) {
  221.             Escape = 1
  222.             break
  223.         }
  224.         else {
  225.             OptErr = "Invalid option: " specGiven Option
  226.             return -3
  227.         }
  228.         }
  229.  
  230.         # Find what the value of the option will be if it takes one.
  231.         # NeedNextOpt is true if the option specifier is the last char of
  232.         # this arg, which means that if the option requires a value it is
  233.         # the next arg.
  234.         if (NeedNextOpt = (ArgInd >= ArgLen)) { # Value is the next arg
  235.         if (GotValue = ArgNum + 1 < argc)
  236.             Value = argv[ArgNum+1]
  237.         }
  238.         else {    # Value is included with option
  239.         Value = substr(Arg,ArgInd + 1)
  240.         GotValue = 1
  241.         }
  242.  
  243.         if (HadValue = AssignVal(Option,Value,Options,
  244.         substr(OptList,Pos + 1,1),GotValue,"",++OptionNum,!NeedNextOpt,
  245.         specGiven)) {
  246.         if (HadValue < 0)    # error occured
  247.             return HadValue
  248.         if (HadValue == 2)
  249.             ArgInd++    # Account for the single-char value we used.
  250.         else {
  251.             if (NeedNextOpt) {    # option took next arg as value
  252.             delete argv[++ArgNum]
  253.             ArgsLeft--
  254.             }
  255.             break    # This option has been used up
  256.         }
  257.         }
  258.     }
  259.     if (Escape)
  260.         break
  261.     # Do not delete arg until after processing of it, so that if it is not
  262.     # recognized it can be left in ARGV[].
  263.     delete argv[ArgNum]
  264.     ArgsLeft--
  265.     }
  266.     if (compress != 0) {
  267.     dest = 1
  268.     src = argc - ArgsLeft + 1
  269.     for (count = ArgsLeft - 1; count; count--) {
  270.         ARGV[dest] = ARGV[src]
  271.         dest++
  272.         src++
  273.     }
  274.     }
  275.     return ArgsLeft
  276. }
  277.  
  278. # Assignment to values in Options[] occurs only in this function.
  279. # Option: Option specifier character.
  280. # Value: Value to be assigned to option, if it takes a value.
  281. # Options[]: Options array to return values in.
  282. # ArgType: Argument type specifier character.
  283. # GotValue: Whether any value is available to be assigned to this option.
  284. # Name: Name of option being processed.
  285. # OptionNum: Number of this option (starting with 1) if set in argv[],
  286. #     or 0 if it was given in a config file or in the environment.
  287. # SingleOpt: true if the value (if any) that is available for this option was
  288. #     given as part of the same command line arg as the option.  Used only for
  289. #     options from the command line.
  290. # specGiven is the option specifier character use, if any (e.g. - or +),
  291. # for use in error messages.
  292. # Global variables: OptErr
  293. # Return value: negative value on error, 0 if option did not require an
  294. # argument, 1 if it did & used the whole arg, 2 if it required just one char of
  295. # the arg.
  296. # Current error values:
  297. # -1: Option that required an argument did not get it.
  298. # -2: Value of incorrect type supplied for option.
  299. # -3: Bad type given for option &
  300. function AssignVal(Option,Value,Options,ArgType,GotValue,Name,OptionNum,
  301. SingleOpt,specGiven,  UsedValue,Err,NumTypes) {
  302.     # If option takes a value...    [
  303.     NumTypes = "*()#<>]"
  304.     if (Option == "&" && ArgType !~ "[" NumTypes) {    # ]
  305.     OptErr = "Bad type given for & option"
  306.     return -3
  307.     }
  308.  
  309.     if (UsedValue = (ArgType ~ "[:;" NumTypes)) {    # ]
  310.     if (!GotValue) {
  311.         if (Name != "")
  312.         OptErr = "Variable requires a value -- " Name
  313.         else
  314.         OptErr = "option requires an argument -- " Option
  315.         return -1
  316.     }
  317.     if ((Err = CheckType(ArgType,Value,Option,Name,specGiven)) != "") {
  318.         OptErr = Err
  319.         return -2
  320.     }
  321.     # Mark this as a numeric variable; will be propogated to Options[] val.
  322.     if (ArgType != ":" && ArgType != ";")
  323.         Value += 0
  324.     if ((Instance = ++Options[Option,"count"]) > 1)
  325.         Options[Option,Instance] = Value
  326.     else
  327.         Options[Option] = Value
  328.     }
  329.     # If this is an environ or rcfile assignment & it was given a value...
  330.     else if (!OptionNum && Value != "") {
  331.     UsedValue = 1
  332.     # If the value is "0" or "-" and this is the first instance of it,
  333.     # do not set Options[Option]; this allows an assignment in an rcfile to
  334.     # turn off an option (for the simple "Option in Options" test) in such
  335.     # a way that it cannot be turned on in a later file.
  336.     if (!(Option in Options) && (Value == "0" || Value == "-"))
  337.         Instance = 1
  338.     else
  339.         Instance = ++Options[Option]
  340.     # Save the value even though this is a flag
  341.     Options[Option,Instance] = Value
  342.     }
  343.     # If this is a command line flag and has a - following it in the same arg,
  344.     # it is being turned off.
  345.     else if (OptionNum && SingleOpt && substr(Value,1,1) == "-") {
  346.     UsedValue = 2
  347.     if (Option in Options)
  348.         Instance = ++Options[Option]
  349.     else
  350.         Instance = 1
  351.     Options[Option,Instance]
  352.     }
  353.     # If this is a flag assignment without a value, increment the count for the
  354.     # flag unless it was turned off.  The indicator for a flag being turned off
  355.     # is that the flag index has not been set in Options[] but it has an
  356.     # instance count.
  357.     else if (Option in Options || !((Option,1) in Options))
  358.     # Increment number of times this flag seen; will inc null value to 1
  359.     Instance = ++Options[Option]
  360.     Options[Option,"num",Instance] = OptionNum
  361.     return UsedValue
  362. }
  363.  
  364. # Option is the option letter
  365. # Value is the value being assigned
  366. # Name is the var name of the option, if any
  367. # ArgType is one of:
  368. # :    String argument
  369. # ;    Non-null string argument
  370. # *    Floating point argument
  371. # (    Non-negative floating point argument
  372. # )    Positive floating point argument
  373. # #    Integer argument
  374. # <    Non-negative integer argument
  375. # >    Positive integer argument
  376. # specGiven is the option specifier character use, if any (e.g. - or +),
  377. # for use in error messages.
  378. # Returns null on success, err string on error
  379. function CheckType(ArgType,Value,Option,Name,specGiven,  Err,ErrStr) {
  380.     if (ArgType == ":")
  381.     return ""
  382.     if (ArgType == ";") {
  383.     if (Value == "")
  384.         Err = "must be a non-empty string"
  385.     }
  386.     # A number begins with optional + or -, and is followed by a string of
  387.     # digits or a decimal with digits before it, after it, or both
  388.     else if (Value !~ /^[-+]?([0-9]+|[0-9]*\.[0-9]+|[0-9]+\.)$/)
  389.     Err = "must be a number"
  390.     else if (ArgType ~ "[#<>]" && Value ~ /\./)
  391.     Err = "may not include a fraction"
  392.     else if (ArgType ~ "[()<>]" && Value < 0)
  393.     Err = "may not be negative"
  394.     # (
  395.     else if (ArgType ~ "[)>]" && Value == 0)
  396.     Err = "must be a positive number"
  397.     if (Err != "") {
  398.     ErrStr = "Bad value \"" Value "\".  Value assigned to "
  399.     if (Name != "")
  400.         return ErrStr "variable " substr(Name,1,1) " " Err
  401.     else {
  402.         if (Option == "&")
  403.         Option = Value
  404.         return ErrStr "option " specGiven substr(Option,1,1) " " Err
  405.     }
  406.     }
  407.     else
  408.     return ""
  409. }
  410.  
  411. # Note: only the above functions are needed by ProcArgs.
  412. # The rest of these functions call ProcArgs() and also do other
  413. # option-processing stuff.
  414.  
  415. # Opts: Process command line arguments.
  416. # Opts processes command line arguments using ProcArgs()
  417. # and checks for errors.  If an error occurs, a message is printed
  418. # and the program is exited.
  419. #
  420. # Input variables:
  421. # Name is the name of the program, for error messages.
  422. # Usage is a usage message, for error messages.
  423. # OptList the option description string, as used by ProcArgs().
  424. # MinArgs is the minimum number of non-option arguments that this
  425. # program should have, non including ARGV[0] and +h.
  426. # If the program does not require any non-option arguments,
  427. # MinArgs should be omitted or given as 0.
  428. # rcFiles, if given, is a colon-seprated list of filenames to read for
  429. # variable initialization.  If a filename begins with ~/, the ~ is replaced
  430. # by the value of the environment variable HOME.  If a filename begins with
  431. # $, the part from the character after the $ up until (but not including)
  432. # the first character not in [a-zA-Z0-9_] will be searched for in the
  433. # environment; if found its value will be substituted, if not the filename will
  434. # be discarded.
  435. # rcfiles are read in the order given.
  436. # Values given in them will not override values given on the command line,
  437. # and values given in later files will not override those set in earlier
  438. # files, because AssignVal() will store each with a different instance index.
  439. # The first instance of each variable, either on the command line or in an
  440. # rcfile, will be stored with no instance index, and this is the value
  441. # normally used by programs that call this function.
  442. # VarNames is a comma-separated list of variable names to map to options,
  443. # in the same order as the options are given in OptList.
  444. # If EnvSearch is given and nonzero, the first EnvSearch variables will also be
  445. # searched for in the environment.  If set to -1, all values will be searched
  446. # for in the environment.  Values given in the environment will override
  447. # those given in the rcfiles but not those given on the command line.
  448. # NoRCopt, if given, is an additional letter option that if given on the
  449. # command line prevents the rcfiles from being read.
  450. # See ProcArgs() for a description of AllowUnRecOpt and optChars, and
  451. # ExclusiveOptions() for a description of exOpts.
  452. # Special options:
  453. # If x is made an option and is given, some debugging info is output.
  454. # h is assumed to be the help option.
  455.  
  456. # Global variables:
  457. # The command line arguments are taken from ARGV[].
  458. # The arguments that are option specifiers and values are removed from
  459. # ARGV[], leaving only ARGV[0] and the non-option arguments.
  460. # The number of elements in ARGV[] should be in ARGC.
  461. # After processing, ARGC is set to the number of elements left in ARGV[].
  462. # The option values are put in Options[].
  463. # On error, Err is set to a positive integer value so it can be checked for in
  464. # an END block.
  465. # Return value: The number of elements left in ARGV is returned.
  466. # Must keep OptErr global since it may be set by InitOpts().
  467. function Opts(Name,Usage,OptList,MinArgs,rcFiles,VarNames,EnvSearch,NoRCopt,
  468. AllowUnrecOpt,optChars,exOpts,  ArgsLeft,e) {
  469.     if (MinArgs == "")
  470.     MinArgs = 0
  471.     ArgsLeft = ProcArgs(ARGC,ARGV,OptList NoRCopt,Options,1,AllowUnrecOpt,
  472.     optChars)
  473.     if (ArgsLeft < (MinArgs+1) && !("h" in Options)) {
  474.     if (ArgsLeft >= 0) {
  475.         OptErr = "Not enough arguments"
  476.         Err = 4
  477.     }
  478.     else
  479.         Err = -ArgsLeft
  480.     printf "%s: %s.\nUse -h for help.\n%s\n",
  481.     Name,OptErr,Usage > "/dev/stderr"
  482.     exit 1
  483.     }
  484.     if (rcFiles != "" && (NoRCopt == "" || !(NoRCopt in Options)) &&
  485.     (e = InitOpts(rcFiles,Options,OptList,VarNames,EnvSearch)) < 0)
  486.     {
  487.     print Name ": " OptErr ".\nUse -h for help." > "/dev/stderr"
  488.     Err = -e
  489.     exit 1
  490.     }
  491.     if ((exOpts != "") && ((OptErr = ExclusiveOptions(exOpts,Options)) != ""))
  492.     {
  493.     printf "%s: Error: %s\n",Name,OptErr > "/dev/stderr"
  494.     Err = 1
  495.     exit 1
  496.     }
  497.     return ArgsLeft
  498. }
  499.  
  500. # ReadConfFile(): Read a file containing var/value assignments, in the form
  501. # <variable-name><assignment-char><value>.
  502. # Whitespace (spaces and tabs) around a variable (leading whitespace on the
  503. # line and whitespace between the variable name and the assignment character) 
  504. # is stripped.  Lines that do not contain an assignment operator or which
  505. # contain a null variable name are ignored, other than possibly being noted in
  506. # the return value.  If more than one assignment is made to a variable, the
  507. # first assignment is used.
  508. # Input variables:
  509. # File is the file to read.
  510. # Comment is the line-comment character.  If it is found as the first non-
  511. #     whitespace character on a line, the line is ignored.
  512. # Assign is the assignment string.  The first instance of Assign on a line
  513. #     separates the variable name from its value.
  514. # If StripWhite is true, whitespace around the value (whitespace between the
  515. #     assignment char and trailing whitespace on the line) is stripped.
  516. # VarPat is a pattern that variable names must match.  
  517. #     Example: "^[a-zA-Z][a-zA-Z0-9]+$"
  518. # If FlagsOK is true, variables are allowed to be "set" by being put alone on
  519. #     a line; no assignment operator is needed.  These variables are set in
  520. #     the output array with a null value.  Lines containing nothing but
  521. #     whitespace are still ignored.
  522. # Output variables:
  523. # Values[] contains the assignments, with the indexes being the variable names
  524. #     and the values being the assigned values.
  525. # Lines[] contains the line number that each variable occured on.  A flag set
  526. #     is record by giving it an index in Lines[] but not in Values[].
  527. # Return value:
  528. # If any errors occur, a string consisting of descriptions of the errors
  529. # separated by newlines is returned.  In no case will the string start with a
  530. # numeric value.  If no errors occur,  the number of lines read is returned.
  531. function ReadConfigFile(Values,Lines,File,Comment,Assign,StripWhite,VarPat,
  532. FlagsOK,
  533. Line,Status,Errs,AssignLen,LineNum,Var,Val) {
  534.     if (Comment != "")
  535.     Comment = "^" Comment
  536.     AssignLen = length(Assign)
  537.     if (VarPat == "")
  538.     VarPat = "."    # null varname not allowed
  539.     while ((Status = (getline Line < File)) == 1) {
  540.     LineNum++
  541.     sub("^[ \t]+","",Line)
  542.     if (Line == "")        # blank line
  543.         continue
  544.     if (Comment != "" && Line ~ Comment)
  545.         continue
  546.     if (Pos = index(Line,Assign)) {
  547.         Var = substr(Line,1,Pos-1)
  548.         Val = substr(Line,Pos+AssignLen)
  549.         if (StripWhite) {
  550.         sub("^[ \t]+","",Val)
  551.         sub("[ \t]+$","",Val)
  552.         }
  553.     }
  554.     else {
  555.         Var = Line    # If no value, var is entire line
  556.         Val = ""
  557.     }
  558.     if (!FlagsOK && Val == "") {
  559.         Errs = Errs \
  560.         sprintf("\nBad assignment on line %d of file %s: %s",
  561.         LineNum,File,Line)
  562.         continue
  563.     }
  564.     sub("[ \t]+$","",Var)
  565.     if (Var !~ VarPat) {
  566.         Errs = Errs sprintf("\nBad variable name on line %d of file %s: %s",
  567.         LineNum,File,Var)
  568.         continue
  569.     }
  570.     if (!(Var in Lines)) {
  571.         Lines[Var] = LineNum
  572.         if (Pos)
  573.         Values[Var] = Val
  574.     }
  575.     }
  576.     if (Status)
  577.     Errs = Errs "\nCould not read file " File
  578.     close(File)
  579.     return Errs == "" ? LineNum : substr(Errs,2)    # Skip first newline
  580. }
  581.  
  582. # Variables:
  583. # Data is stored in Options[].
  584. # rcFiles, OptList, VarNames, and EnvSearch are as as described for Opts().
  585. # Global vars:
  586. # Sets OptErr.  Uses ENVIRON[].
  587. # If anything is read from any of the rcfiles, sets READ_RCFILE to 1.
  588. function InitOpts(rcFiles,Options,OptList,VarNames,EnvSearch,
  589. Line,Var,Pos,Vars,Map,CharOpt,NumVars,TypesInd,Types,Type,Ret,i,rcFile,
  590. fNames,numrcFiles,filesRead,Err,Values,retStr) {
  591.     split("",filesRead,"")    # make awk know this is an array
  592.     NumVars = split(VarNames,Vars,",")
  593.     TypesInd = Ret = 0
  594.     if (EnvSearch == -1)
  595.     EnvSearch = NumVars
  596.     for (i = 1; i <= NumVars; i++) {
  597.     Var = Vars[i]
  598.     CharOpt = substr(OptList,++TypesInd,1)
  599.     if (CharOpt ~ "^[:;*()#<>&]$")
  600.         CharOpt = substr(OptList,++TypesInd,1)
  601.     Map[Var] = CharOpt
  602.     Types[Var] = Type = substr(OptList,TypesInd+1,1)
  603.     # Do not overwrite entries from environment
  604.     if (i <= EnvSearch && Var in ENVIRON &&
  605.     (Err = AssignVal(CharOpt,ENVIRON[Var],Options,Type,1,Var,0)) < 0)
  606.         return Err
  607.     }
  608.  
  609.     numrcFiles = split(rcFiles,fNames,":")
  610.     for (i = 1; i <= numrcFiles; i++) {
  611.     rcFile = fNames[i]
  612.     if (rcFile ~ "^~/")
  613.         rcFile = ENVIRON["HOME"] substr(rcFile,2)
  614.     else if (rcFile ~ /^\$/) {
  615.         rcFile = substr(rcFile,2)
  616.         match(rcFile,"^[a-zA-Z0-9_]*")
  617.         envvar = substr(rcFile,1,RLENGTH)
  618.         if (envvar in ENVIRON)
  619.         rcFile = ENVIRON[envvar] substr(rcFile,RLENGTH+1)
  620.         else
  621.         continue
  622.     }
  623.     if (rcFile in filesRead)
  624.         continue
  625.     # rcfiles are liable to be given more than once, e.g. UHOME and HOME
  626.     # may be the same
  627.     filesRead[rcFile]
  628.     if ("x" in Options)
  629.         printf "Reading configuration file %s\n",rcFile > "/dev/stderr"
  630.     retStr = ReadConfigFile(Values,Lines,rcFile,"#","=",0,"",1)
  631.     if (retStr > 0)
  632.         READ_RCFILE = 1
  633.     else if (ret != "") {
  634.         OptErr = retStr
  635.         Ret = -1
  636.     }
  637.     for (Var in Lines)
  638.         if (Var in Map) {
  639.         if ((Err = AssignVal(Map[Var],
  640.         Var in Values ? Values[Var] : "",Options,Types[Var],
  641.         Var in Values,Var,0)) < 0)
  642.             return Err
  643.         }
  644.         else {
  645.         OptErr = sprintf(\
  646.         "Unknown var \"%s\" assigned to on line %d\nof file %s",Var,
  647.         Lines[Var],rcFile)
  648.         Ret = -1
  649.         }
  650.     }
  651.  
  652.     if ("x" in Options)
  653.     for (Var in Map)
  654.         if (Map[Var] in Options)
  655.         printf "(%s) %s=%s\n",Map[Var],Var,Options[Map[Var]] > \
  656.         "/dev/stderr"
  657.         else
  658.         printf "(%s) %s not set\n",Map[Var],Var > "/dev/stderr"
  659.     return Ret
  660. }
  661.  
  662. # OptSets is a semicolon-separated list of sets of option sets.
  663. # Within a list of option sets, the option sets are separated by commas.  For
  664. # each set of sets, if any option in one of the sets is in Options[] AND any
  665. # option in one of the other sets is in Options[], an error string is returned.
  666. # If no conflicts are found, nothing is returned.
  667. # Example: if OptSets = "ab,def,g;i,j", an error will be returned due to
  668. # the exclusions presented by the first set of sets (ab,def,g) if:
  669. # (a or b is in Options[]) AND (d, e, or f is in Options[]) OR
  670. # (a or b is in Options[]) AND (g is in Options) OR
  671. # (d, e, or f is in Options[]) AND (g is in Options)
  672. # An error will be returned due to the exclusions presented by the second set
  673. # of sets (i,j) if: (i is in Options[]) AND (j is in Options[]).
  674. # todo: make options given on command line unset options given in config file
  675. # todo: that they conflict with.
  676. function ExclusiveOptions(OptSets,Options,
  677. Sets,SetSet,NumSets,Pos1,Pos2,Len,s1,s2,c1,c2,ErrStr,L1,L2,SetSets,NumSetSets,
  678. SetNum,OSetNum) {
  679.     NumSetSets = split(OptSets,SetSets,";")
  680.     # For each set of sets...
  681.     for (SetSet = 1; SetSet <= NumSetSets; SetSet++) {
  682.     # NumSets is the number of sets in this set of sets.
  683.     NumSets = split(SetSets[SetSet],Sets,",")
  684.     # For each set in a set of sets except the last...
  685.     for (SetNum = 1; SetNum < NumSets; SetNum++) {
  686.         s1 = Sets[SetNum]
  687.         L1 = length(s1)
  688.         for (Pos1 = 1; Pos1 <= L1; Pos1++)
  689.         # If any of the options in this set was given, check whether
  690.         # any of the options in the other sets was given.  Only check
  691.         # later sets since earlier sets will have already been checked
  692.         # against this set.
  693.         if ((c1 = substr(s1,Pos1,1)) in Options)
  694.             for (OSetNum = SetNum+1; OSetNum <= NumSets; OSetNum++) {
  695.             s2 = Sets[OSetNum]
  696.             L2 = length(s2)
  697.             for (Pos2 = 1; Pos2 <= L2; Pos2++)
  698.                 if ((c2 = substr(s2,Pos2,1)) in Options)
  699.                 ErrStr = ErrStr "\n"\
  700.                 sprintf("Cannot give both %s and %s options.",
  701.                 c1,c2)
  702.             }
  703.     }
  704.     }
  705.     if (ErrStr != "")
  706.     return substr(ErrStr,2)
  707.     return ""
  708. }
  709.  
  710. # The value of each instance of option Opt that occurs in Options[] is made an
  711. # index of Set[].
  712. # The return value is the number of instances of Opt in Options.
  713. function Opt2Set(Options,Opt,Set,  count) {
  714.     if (!(Opt in Options))
  715.     return 0
  716.     Set[Options[Opt]]
  717.     count = Options[Opt,"count"]
  718.     for (; count > 1; count--)
  719.     Set[Options[Opt,count]]
  720.     return count
  721. }
  722.  
  723. # The value of each instance of option Opt that occurs in Options[] that
  724. # begins with "!" is made an index of nSet[] (with the ! stripped from it).
  725. # Other values are made indexes of Set[].
  726. # The return value is the number of instances of Opt in Options.
  727. function Opt2Sets(Options,Opt,Set,nSet,  count,aSet,ret) {
  728.     ret = Opt2Set(Options,Opt,aSet)
  729.     for (value in aSet)
  730.     if (substr(value,1,1) == "!")
  731.         nSet[substr(value,2)]
  732.     else
  733.         Set[value]
  734.     return ret
  735. }
  736.  
  737. # Returns true if option Opt was given on the command line.
  738. function CmdLineOpt(Options,Opt,  i) {
  739.     for (i = 1; (Opt,"num",i) in Options; i++)
  740.     if (Options[Opt,"num",i] != 0)
  741.         return 1
  742.     return 0
  743. }
  744. ### End of ProcArgs library
  745. ### Begin utty,id routines
  746.  
  747. # utty: find ttys a user is logged in on.
  748. # For each tty User is logged in on, an element is created in TTYs[].
  749. # The index is the name of the tty, with a leading "/dev/".
  750. # The value is set to 1 if the user is writable on that tty, 0 if not.
  751. # The number of ttys the user is logged in on is returned.
  752. function utty(User,TTYs,  Cmd,Count) {
  753.     Cmd = "exec who -T"
  754.     Count = 0
  755.     while ((Cmd | getline) == 1)
  756.     if ($1 == User) {
  757.         if ($2 == "+")
  758.         TTYs[$3] = 1
  759.         else
  760.         TTYs[$3] = 0
  761.         Count++
  762.     }
  763.     close(Cmd)
  764.     return Count
  765. }
  766.  
  767. # id returns the user name of the user who owns the current process.
  768. # In the array IDs, elements are set as follows:
  769. # uid: numeric user id
  770. # gid: numeric group id
  771. # group: group name, if any
  772. # user: user name, if any
  773. function id(IDs,  Cmd,line,elem) {
  774.     Cmd = "exec id"
  775.     Cmd | getline line
  776.     split(line,elem,"[()=]")
  777.     close(Cmd)
  778.     IDs["user"] = elem[3]
  779.     IDs["gid"] = elem[5]
  780.     IDs["group"] = elem[6]
  781.     return IDs["uid"] = elem[2]
  782. }
  783.  
  784. ### End utty,id routines
  785.